/**
 * 获取query参数中间件
 */
import { typeOf } from '../utils/common';
export default () => {
    return async(ctx, next) => {
        try {
            ctx.getQueryString = (fields, defaultValue = null) => {
                if (!fields) {
                    throw error('请传入参数');
                }
                const query = ctx.request.query
                let type = typeOf(fields);
                if (type === 'string') {
                    const value = query[fields] || defaultValue;
                    return value;
                } else if (type === 'array') {
                    let ret = {};
                    for (let index = 0; index < fields.length; index++) {
                        const key = fields[index];
                        ret[key] = query[key] || null;
                    }
                    return ret;
                } else {
                    if (!fields) {
                        throw error('请传入合法参数类型：string | array');
                    }
                }

            }

            ctx.getQueryNumber = (fields, defaultValue = null) => {
                if (!fields) {
                    throw error('请传入参数');
                }
                const query = ctx.request.query
                let type = typeOf(fields);
                if (type === 'string') {
                    const value = query[fields] || defaultValue;
                    return Number(value);
                } else if (type === 'array') {
                    let ret = {};
                    for (let index = 0; index < fields.length; index++) {
                        const key = fields[index];
                        if (key || key == 0) {
                            ret[key] = Number(query[key]);
                        } else {
                            ret[key] = null;
                        }
                    }
                    return ret;
                } else {
                    if (!fields) {
                        throw error('请传入合法参数类型：string | array');
                    }
                }

            }
        } catch (error) {
            console.log('error', error);

        }
        await next();
    }
}